import { useAsync, useSetState } from "react-use";
import InfiniteScroll, {
  InfiniteScrollLoading,
} from "../components/InfiniteScroll";
import { SwitchButton } from "../components/SwitchButton";
import {
  App,
  Avatar,
  Button,
  Divider,
  Drawer,
  Form,
  Input,
  Skeleton,
} from "antd";
import { useAuthStore } from "../store/auth";
import { GoodsCard } from "../components/GoodsCard";
import { clsx } from "../common/utils";
import Masonry from "react-masonry-css";
import { ResBody, request } from "../common/request";
import React, { useCallback, useEffect } from "react";
import { UpAvatar } from "../components/Upfile";
import {
  useParams,
  useNavigate,
  useLocation,
  Outlet,
  useOutletContext,
} from "react-router-dom";
import { GoodsModel, UserModel } from "../common/model";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { DefaultAvatar } from "../common/constant";
import { useSystemStore } from "../store/system";

const UPage: React.FC = () => {
  const { account } = useParams();
  const system = useSystemStore();
  const auth = useAuthStore();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const lo = useLocation();

  const [state, setState] = useSetState({
    user: undefined as undefined | UserModel, //当前user
    userLoading: false, //user加载
    userEditOpen: false, //用户信息编辑弹窗
    followed: false, //关注情况
    isMe: false,
  });

  useAsync(async () => {
    if (state.user) {
      if (auth.user?.account === account) {
        return setState({ followed: false });
      }
      const ret = await request.get<any, ResBody>(
        `/api/relation/follow/${state.user.id}`
      );
      if (ret.code === 200) {
        setState({ followed: ret.followed });
      }
    }
  }, [state.user, auth.user]);

  useEffect(() => {
    //检测退出登录后
    if (auth.user?.account === account) {
      setState({ isMe: true, user: auth.user });
    } else {
      setState({ isMe: false });
    }
  }, [auth.user]);

  useAsync(async () => {
    if (auth.user?.account === account) {
      setState({ user: auth.user, isMe: true });
    } else {
      setState({ userLoading: true });
      const ret = await request.get<any, ResBody>(
        `/api/user/info?account=${account}`
      );
      if (ret.code === 200) {
        setState({ user: ret.user, isMe: false, userLoading: false });
      } else {
        setState({ userLoading: false });
      }
    }
  }, [account]);

  const onFinish = async () => {
    const data = form.getFieldsValue();
    const ret = await request.post<any, ResBody>(`/api/user/info`, data);
    if (ret.code === 200) {
      auth.setUser(ret.user);
      system.message("success", "修改成功");
      setState({ userEditOpen: false });
      return;
    }
  };

  const onSwitchFollow = async () => {
    const ret = await request.post<any, ResBody>(
      `/api/relation/switch-follow/${state.user?.id}`
    );
    if (ret.code === 200) {
      setState({ followed: ret.followed });
      system.message("success", ret.msg);
    }
  };

  return (
    <>
      <Drawer
        title="用户设置"
        width={600}
        onClose={() => setState({ userEditOpen: false })}
        open={state.userEditOpen}
        bodyStyle={{ paddingBottom: 80 }}
        afterOpenChange={(open) => {
          if (open) {
            form.setFieldsValue(auth.user);
          }
        }}
      >
        <Form
          form={form}
          onFinish={onFinish}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          layout="horizontal"
        >
          <Form.Item
            name="avatar"
            label="头像"
            initialValue={auth.user?.avatar}
          >
            <UpAvatar />
          </Form.Item>
          <Form.Item
            label="昵称"
            required
            name="nickname"
            initialValue={auth.user?.nickname}
            rules={[{ required: true, message: "请填写昵称" }]}
          >
            <Input size="large" />
          </Form.Item>
          <Form.Item label="简介" name="intro" initialValue={auth.user?.intro}>
            <Input.TextArea
              size="large"
              placeholder="介绍一下自己"
              showCount
              maxLength={100}
              autoSize={{ minRows: 4, maxRows: 6 }}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{ offset: 0, span: 20, sm: { offset: 4 } }}
            className=" mt-10"
          >
            <Button
              type="primary"
              htmlType="submit"
              size="large"
              className="w-full"
            >
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>

      <Skeleton loading={state.userLoading}>
        {state.user && (
          <>
            <div className={clsx("flex items-center", "mb-7 pr-2 sm:px-20")}>
              <Avatar
                size={80}
                className="border-none"
                src={
                  <img
                    src={
                      state.user?.avatar ? state.user?.avatar : DefaultAvatar
                    }
                    alt=""
                  />
                }
              />
              <div className="mx-6 flex-1 overflow-hidden">
                <div className="font-bold text-2xl">{state.user?.nickname}</div>
                <div className="text-font2">{state.user?.intro}</div>
              </div>

              {state.isMe ? (
                <Button
                  type="text"
                  size="large"
                  shape="round"
                  className="font-bold"
                  onClick={() => setState({ userEditOpen: true })}
                >
                  编辑
                </Button>
              ) : (
                <Button
                  type="primary"
                  size="large"
                  shape="round"
                  className="font-bold !bg-active hover:!bg-active/90"
                  onClick={onSwitchFollow}
                >
                  {state.followed ? "取消关注" : "关注"}
                </Button>
              )}
            </div>

            <SwitchButton
              data={[
                { label: "发布", value: "publish" },
                { label: "收藏", value: "collect" },
                { label: "已购买", value: "buy" },
                { label: "关注", value: "follow" },
              ]}
              defaultValue={
                lo.pathname.includes("collect")
                  ? "collect"
                  : lo.pathname.includes("buy")
                  ? "buy"
                  : lo.pathname.includes("follow")
                  ? "follow"
                  : "publish"
              }
              onChange={(value) => {
                navigate(value === "publish" ? "" : value);
              }}
            />
            <Divider />
            <div className="h-2" />
            <Outlet
              context={
                {
                  user: state.user,
                  isMe: state.isMe,
                } satisfies OutletContextType
              }
            />
          </>
        )}
      </Skeleton>
    </>
  );
};

interface OutletContextType {
  user: UserModel;
  isMe: boolean;
}

export default UPage;

export const UPublish: React.FC = () => {
  const { user, isMe } = useOutletContext<OutletContextType>();
  const { modal } = App.useApp();
  const system = useSystemStore();
  const auth = useAuthStore();
  const [state, setState] = useSetState({
    page: 1,
    data: [] as GoodsModel[],
    total: -1,
    loading: false as InfiniteScrollLoading,
  });

  useEffect(() => {
    next(true);
  }, [user.id, auth.user?.id]);

  const next = useCallback(
    async (init?: boolean) => {
      setState({ loading: init ? "reload" : "loadmore" });
      const ret = await request.get<any, ResBody>("/api/goods/query", {
        params: {
          page: init ? 1 : state.page,
          page_size: 10,
          uid: user.id,
        },
      });
      if (ret?.code === 200) {
        // console.log(ret);
        setState((e) => ({
          data: init ? ret.goods : e.data.concat(ret.goods),
          total: ret.total,
          page: init ? 2 : state.page + 1,
          loading: false,
        }));
      } else {
        setState({ loading: false });
      }
    },
    [state.page, user]
  );

  const deleteGoods = useCallback(async (id: number) => {
    modal.confirm({
      centered: true,
      title: "你确定要删除吗?",
      icon: <ExclamationCircleFilled />,
      content: "删除后将不可恢复",
      okText: "确认",
      cancelText: "取消",
      maskClosable: true,
      async onOk() {
        const ret = await request.delete<any, ResBody>(
          `/api/goods/delete/${id}`
        );
        if (ret?.code === 200) {
          system.message("success", ret.msg);
          setState((e) => ({
            data: e.data.filter((d) => d.id !== id),
            total: e.total - 1,
          }));
        }
      },
    });
  }, []);

  return (
    <>
      {user && (
        <InfiniteScroll
          loading={state.loading}
          next={next}
          hasMore={state.total - state.data.length > 0}
          total={state.total}
        >
          <Masonry
            breakpointCols={{ default: 3, 1000: 2 }}
            className="my-masonry-grid"
            columnClassName="my-masonry-grid_column"
          >
            {state.data.map((d) => (
              <GoodsCard
                key={d.id}
                data={d}
                onDeleteClick={deleteGoods}
                showAction={isMe}
                onLikeSwitch={(gid, liked_id) => {
                  setState({
                    data: state.data.map((d) =>
                      d.id === gid
                        ? {
                            ...d,
                            like_count: liked_id
                              ? d.like_count + 1
                              : d.like_count - 1,
                            liked_id,
                          }
                        : d
                    ),
                  });
                }}
              />
            ))}
          </Masonry>
        </InfiniteScroll>
      )}
    </>
  );
};

export const UCollect: React.FC = () => {
  const { user } = useOutletContext<OutletContextType>();
  const auth = useAuthStore();
  const [state, setState] = useSetState({
    page: 1,
    data: [] as GoodsModel[],
    total: -1,
    loading: false as InfiniteScrollLoading,
  });

  useEffect(() => {
    //偶尔 触发两次bug，需要观察
    next(true);
  }, [user.id, auth.user?.id]);

  const next = useCallback(
    async (init?: boolean) => {
      setState({ loading: init ? "reload" : "loadmore" });
      const ret = await request.get<any, ResBody>("/api/goods/query-collect", {
        params: {
          page: init ? 1 : state.page,
          page_size: 10,
          uid: user.id,
        },
      });
      if (ret.code === 200) {
        // console.log(ret);
        setState((e) => ({
          data: init ? ret.goods : e.data.concat(ret.goods),
          total: ret.total,
          page: init ? 2 : state.page + 1,
          loading: false,
        }));
      } else {
        setState({ loading: false });
      }
    },
    [state.page, user]
  );

  return (
    <>
      {user && (
        <InfiniteScroll
          loading={state.loading}
          next={next}
          hasMore={state.total - state.data.length > 0}
          total={state.total}
        >
          <Masonry
            breakpointCols={{ default: 3, 1000: 2 }}
            className="my-masonry-grid"
            columnClassName="my-masonry-grid_column"
          >
            {state.data.map((d) => (
              <GoodsCard
                key={d.id}
                data={d}
                onLikeSwitch={(gid, liked_id) => {
                  setState({
                    data: state.data.map((d) =>
                      d.id === gid
                        ? {
                            ...d,
                            like_count: liked_id
                              ? d.like_count + 1
                              : d.like_count - 1,
                            liked_id,
                          }
                        : d
                    ),
                  });
                }}
              />
            ))}
          </Masonry>
        </InfiniteScroll>
      )}
    </>
  );
};

export const UBuy: React.FC = () => {
  const { user } = useOutletContext<OutletContextType>();
  const auth = useAuthStore();
  const [state, setState] = useSetState({
    page: 1,
    data: [] as GoodsModel[],
    total: -1,
    loading: false as InfiniteScrollLoading,
  });

  useEffect(() => {
    //偶尔 触发两次bug，需要观察
    next(true);
  }, [user.id, auth.user?.id]);

  const next = useCallback(
    async (init?: boolean) => {
      setState({ loading: init ? "reload" : "loadmore" });
      const ret = await request.get<ResBody>("/api/goods/buy", {
        params: {
          page: init ? 1 : state.page,
          page_size: 10,
          uid: user.id,
        },
      });
      if (ret.data?.code === 200) {
        // console.log(ret);
        setState((e) => ({
          data: init ? ret.data.result : e.data.concat(ret.data.result),
          total: ret.data.info?.total,
          page: init ? 2 : state.page + 1,
          loading: false,
        }));
      } else {
        setState({ loading: false });
      }
    },
    [state.page, user]
  );

  return (
    <>
      {user && (
        <InfiniteScroll
          loading={state.loading}
          next={next}
          hasMore={state.total - state.data.length > 0}
          total={state.total}
        >
          <Masonry
            breakpointCols={{ default: 3, 1000: 2 }}
            className="my-masonry-grid"
            columnClassName="my-masonry-grid_column"
          >
            {state.data.map((d) => (
              <GoodsCard
                key={d.id}
                data={d}
                onLikeSwitch={(gid, liked_id) => {
                  setState({
                    data: state.data.map((d) =>
                      d.id === gid
                        ? {
                            ...d,
                            like_count: liked_id
                              ? d.like_count + 1
                              : d.like_count - 1,
                            liked_id,
                          }
                        : d
                    ),
                  });
                }}
              />
            ))}
          </Masonry>
        </InfiniteScroll>
      )}
    </>
  );
};
